import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class DeltaMode extends StatefulWidget {
  const DeltaMode({super.key});
  @override
  State<DeltaMode> createState() => _DeltaModeState();
}

class _DeltaModeState extends State<DeltaMode>
    implements DeltaTextInputClient {
  late final TextInputConnection _conn;
  TextEditingValue _value = const TextEditingValue(text: 'Hello');
  final List<String> _logs = [];
  final FocusNode _focusNode = FocusNode();
  final TextEditingController _controller = TextEditingController();

  /* ===== DeltaTextInputClient ===== */
  @override
  TextEditingValue get currentTextEditingValue => _value;

  @override
  void updateEditingValueWithDeltas(List<TextEditingDelta> deltas) {
    print("DeLTA TEST ===> updateEditingValueWithDeltas ------${deltas}");

    for (final d in deltas) {
      if (d is TextEditingDeltaDeletion) {
        _logs.add('Δ 删除: "${d.textDeleted}" @${d.deletedRange.start}-${d.deletedRange.end}');
      } else if (d is TextEditingDeltaInsertion) {
        _logs.add('Δ 插入: "${d.textInserted}" @${d.composing.start}');
      } else if (d is TextEditingDeltaReplacement) {
        _logs.add('Δ 替换: "${d.textReplaced}"→"${d.replacementText}" @${d.replacedRange.start}-${d.replacedRange.end}');
      }
    }
    setState(() {
      for (final d in deltas){
        _value = d.apply(_value);
        _controller.value = _value;
      };
    });
  }

  @override
  void updateEditingValue(TextEditingValue value) {
    if (_value.text.length > value.text.length) {
      final diff = _value.text.length - value.text.length;
      final start = _value.selection.baseOffset - diff;
      final deletedText = _value.text.substring(start, _value.selection.baseOffset);
      _logs.add('Δ 删除: "$deletedText" @${start}-${_value.selection.baseOffset}');
    }
    setState(() {
      _value = value;
    });
  }

  /* ===== 其余空实现 ===== */
  @override
  void performAction(TextInputAction action) {}
  @override
  void connectionClosed() {}

  @override
  void insertContent(KeyboardInsertedContent content) {}
  @override
  void insertTextPlaceholder(Size size) {}
  @override
  void performPrivateCommand(String action, Map<String, dynamic> data) {}
  @override
  void performSelector(String selectorName) {}
  @override
  void removeTextPlaceholder() {}
  @override
  void showAutocorrectionPromptRect(int start, int end) {}
  @override
  void showToolbar() {}
  @override
  void updateFloatingCursor(RawFloatingCursorPoint point) {}

  /* ===== 生命周期 ===== */
  @override
  void initState() {
    super.initState();
    _controller.text = _value.text;
    _conn = TextInput.attach(
      this,
      const TextInputConfiguration(
        enableDeltaModel: true,
        inputType: TextInputType.text,
      ),
    )
      ..show()
      ..setEditingState(_value);
    // _focusNode.requestFocus();
  }

  @override
  void dispose() {
    _conn.close();
    _focusNode.dispose();
    super.dispose();
  }

  /* ===== UI ===== */
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Delta 模式')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: _logs.length,
              itemBuilder: (_, i) => Text(_logs[i],
                  style: const TextStyle(fontSize: 12, fontFamily: 'monospace')),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: Shortcuts(
              shortcuts: {
                LogicalKeySet(LogicalKeyboardKey.backspace): const DeleteIntent(),
              },
              child: Actions(
                actions: {
                  DeleteIntent: CallbackAction<DeleteIntent>(
                    onInvoke: (intent) {
                      var a = 1;
                      // 处理删除操作
                      final diff = _value.text.length - _controller.text.length;
                      final start = _value.selection.baseOffset - diff;
                      final deletedText = _value.text.substring(start, _value.selection.baseOffset);
                      // _logs.add('Δ 删除: "$deletedText" @${start}-${_value.selection.baseOffset}');
                    },
                  ),
                },
                child: TextField(
                  controller: _controller,
                  focusNode: _focusNode,
                  decoration: const InputDecoration(
                    hintText: '输入/删除/替换...（Delta 监听）',
                    border: OutlineInputBorder(),
                  ),
                  onChanged: (_) {
                    setState(() {

                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement currentAutofillScope
  AutofillScope? get currentAutofillScope => throw UnimplementedError();

  @override
  void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
    // TODO: implement didChangeInputControl
  }
}

class DeleteIntent extends Intent {
  const DeleteIntent();
}